var publicApi = require('../../script/public.js');
var orderApi = require('../../script/order.js');
var revenueApi = require('../../script/revenue.js');
import tool from '../../utils/common.js';
import printer from '../../utils/bluetoothPrinter.js';
const iconv = require('iconv-lite');
var timer;
var blueTimer;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    UserList: [],
    SearchParams: {
      Area_Code_Dept: '',
      DEPT_NAME: '',
      Area_Code_Building: '',
      LOU_NAME: '',
      Area_Code_Unit: '',
      CONS_NO: '',
      CONS_NAME: '',
      // PhoneNumber: '',
      Room: '',
    },
    pagination: {
      page: 1,
      rows: 30,
      sidx: '',
      sord: ''
    },
    HasNextPage: true,
    noData: false,
    isReachBottom: false,
    // 弹窗
    ShowPop: false,
    DeptShow: false,
    DeptList: [],
    DeptListShow: [],
    BuildingShow: false,
    BuildingList: [],
    BuildingListShow: [],
    CustomStyle: '',
    position: '',
    // 蓝牙打印
    PrintPop: false,
    isSearching: false,
    isConnected: false,
    isConnecting: false,
    status: '未连接',
    currentDevice: null,
    printing: false,
    OrderInfo: null,
    // OrderInfo: {
    //   ConsNo: 'LF938943',
    //   ConsName: '测试用户',
    //   PayTime: '2025-10-24 18:15:48',
    //   OperatorName: '管理员',
    //   Detail: [],
    //   OrderMoney: 123,
    //   DiscountCost: 0,
    //   DelayCost: 0,
    //   AccountMoney: 123,
    //   CompanyName: '测试',
    //   CompanyPhone: '133556669'
    // },
    devices: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 设置回调函数
    // printer.onStatusChange((status) => {
    //   this.setData({
    //     status
    //   });
    //   console.log(this.data.status);
    // });
    printer.onStopSearch((status) => {
      this.setData({
        isSearching: false,
      });
    });
    printer.onDeviceFound((devices) => {
      if (this.data.isConnecting || this.data.isConnected) return;
      this.setData({
        isSearching: false,
        currentDevice: devices[0],
        devices
      });
      wx.showToast({
        title: '发现蓝牙设备',
        icon: 'none'
      });
      // if (this.data.isConnecting) return;
      this.connectDevice();
    });

    printer.onConnected((deviceId) => {
      this.setData({
        isConnected: true,
        isConnecting: false,
        status: `已连接到 ${deviceId}`
      });
      wx.showToast({
        title: '蓝牙打印机连接成功',
        icon: 'none'
      });
    });

    printer.onDisconnected(() => {
      this.setData({
        isConnecting: false,
        status: '连接已断开'
      });
      wx.showToast({
        title: '连接已断开',
        icon: 'none'
      });
    });

    // 初始化蓝牙模块
    this.initBluetooth();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this._refreshData();
    this.getDepts();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    printer.disconnect();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    wx.showNavigationBarLoading();
    this._refreshData();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    this.setData({
      isReachBottom: true
    });
    if (this.data.HasNextPages) {
      this.setData({
        'pagination.page': this.data.pagination.page + 1
      })
      this.searchUser();
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  _refreshData() {
    this.setData({
      pagination: {
        page: 1,
        rows: 30,
        sidx: '',
        sord: ''
      },
      SearchParams: {
        Area_Code_Dept: '',
        DEPT_NAME: '',
        Area_Code_Building: '',
        LOU_NAME: '',
        Area_Code_Unit: '',
        CONS_NO: '',
        CONS_NAME: '',
        // PhoneNumber: '',
        Room: ''
      },
      HasNextPage: true,
      noData: false,
      isReachBottom: false,
      BuildingList: [],
    });
    this.searchUser(true);
  },
  searchChange: tool.debounce(function (e) {
    const ev = e[0];
    this.setData({
      'SearchParams.CONS_NO': ev.detail.value,
    });
    this.doSearch();
  }, 600),
  openFilter() {
    this.setData({
      PrintPop: false,
      ShowPop: true,
      position: 'right',
      CustomStyle: 'width: 80%;height:100%;margin-left:20%;border-radius: 10px 0 0 10px;'
    });
  },
  getDepts() {
    const params = {
      queryParam: {
        DropType: 1,
        Param_0: ''
      },
      pagination: {
        rows: 10000,
        page: 1,
        sidx: "",
        sord: ""
      }
    }
    publicApi.GetDropDownList_Page(params).then(res => {
      if (res.code === 200) {
        this.setData({
          DeptList: res.data.Items,
          DeptListShow: res.data.Items,
        });
      }
    })
  },
  getBuilding() {
    const params = {
      queryParam: {
        DropType: 3,
        Param_0: '',
        Param_1: this.data.SearchParams.Area_Code_Dept,
        Param_2: ""
      },
      pagination: {
        rows: 10000,
        page: 1,
        sidx: "",
        sord: ""
      }
    }
    publicApi.GetDropDownList_Page(params).then(res => {
      if (res.code === 200) {
        this.setData({
          BuildingList: res.data.Items,
          BuildingListShow: res.data.Items,
        });
      }
    })
  },
  openSearch() {
    this.setData({
      ShowPop: true
    });
  },
  leave() {},
  searchUser(isRefresh) {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    const params = {
      queryParam: {
        Area_Code_Dept: this.data.SearchParams.Area_Code_Dept,
        Area_Code_Building: this.data.SearchParams.Area_Code_Building,
        Area_Code_Unit: this.data.SearchParams.Area_Code_Unit,
        CONS_NO: this.data.SearchParams.CONS_NO,
        CONS_NAME: this.data.SearchParams.CONS_NAME,
        // PhoneNumber: this.data.SearchParams.PhoneNumber,
        Room: this.data.SearchParams.Room,
      },
      pagination: {
        ...this.data.pagination
      }
    }
    revenueApi.GetMyOrderList(params).then(res => {
      wx.hideNavigationBarLoading();
      wx.stopPullDownRefresh();
      wx.hideLoading();
      if (res.code === 200) {
        let dataList = []
        if (isRefresh) {
          dataList = [...res.data.rows]
        } else {
          dataList = [...this.data.UserList, ...res.data.rows]
        }
        const noData = dataList.length === 0
        this.setData({
          UserList: dataList,
          HasNextPages: res.data.HasNextPages,
          noData: noData
        })
      }
    }).catch(_err => {
      wx.hideLoading();
    });
  },
  showPopup(e) {
    const popupType = e.currentTarget.dataset.pop;
    if (popupType === 'Building' && this.data.SearchParams.Area_Code_Dept === '') {
      wx.showToast({
        title: '请先选择小区',
        icon: 'none'
      });
      return;
    }
    this.setData({
      [popupType + 'Show']: true
    });
  },
  closePop(e) {
    const popupType = e.currentTarget.dataset.pop;
    this.setData({
      [popupType + 'Show']: false,
      searchText: '',
      DeptListShow: [...this.data.DeptList],
      BuildingListShow: []
    });
  },
  searchDeptChange(e) {
    let val = e.detail.value;
    clearTimeout(this.timer);
    this.timer = setTimeout(() => {
      const list = [...this.data.DeptList];
      const newList = list.filter(item => {
        return item.Label.indexOf(val) > -1
      })
      this.setData({
        searchText: val,
        DeptListShow: newList
      });
    })
  },
  selectDept(e) {
    const dept = e.currentTarget.dataset.info;
    this.setData({
      'SearchParams.Area_Code_Dept': dept.Value,
      'SearchParams.DEPT_NAME': dept.Label,
      DeptShow: false
    });
    this.getBuilding();
  },
  searchBuildingChange(e) {
    let val = e.detail.value;
    clearTimeout(this.timer);
    this.timer = setTimeout(() => {
      const list = [...this.data.BuildingList];
      const newList = list.filter(item => {
        return item.Label.indexOf(val) > -1
      })
      this.setData({
        searchText: val,
        BuildingListShow: newList
      });
    })
  },
  selectBuilding(e) {
    const dept = e.currentTarget.dataset.info;
    this.setData({
      'SearchParams.Area_Code_Building': dept.Value,
      'SearchParams.LOU_NAME': dept.Label,
      BuildingShow: false
    });
  },
  inputChange(e) {
    const type = e.currentTarget.dataset.type;
    let val = e.detail.value;
    this.setData({
      ['SearchParams.' + type]: val
    });
  },
  reset() {
    this.setData({
      SearchParams: {
        Area_Code_Dept: '',
        DEPT_NAME: '',
        Area_Code_Building: '',
        LOU_NAME: '',
        Area_Code_Unit: '',
        CONS_NO: '',
        CONS_NAME: '',
        // PhoneNumber: '',
        Room: ''
      },
    })
  },
  doSearch() {
    this.setData({
      pagination: {
        page: 1,
        rows: 30,
        sidx: '',
        sord: ''
      },
      HasNextPage: true,
      noData: false,
      isReachBottom: false,
      ShowPop: false
    });
    this.searchUser(true);
  },
  toPage: function (e) {
    const route = e.currentTarget.dataset.route;
    const user = e.currentTarget.dataset.user;
    wx.navigateTo({
      url: '../' + route + '/' + route + '?CONS_NO=' + user.CONS_NO + '&CONS_NAME=' + user.CONS_NAME + '&addr=' + user.WATER_ADDR
    })
  },
  /************ 蓝牙打印功能 ********************/
  // 1、初始化蓝牙
  async initBluetooth() {
    try {
      await printer.initBluetooth();
      this.setData({
        isSearching: true,
        currentDevice: null
      });
      this.searchDevices();
      wx.showToast({
        title: '初始化蓝牙适配器成功',
        icon: 'none'
      });
    } catch (err) {
      wx.showToast({
        title: '请检查手机蓝牙是否开启',
        icon: 'none'
      });
    }
  },
  // 2、搜索设备
  async searchDevices() {
    // this.setData({
    //   isSearching: true,
    //   currentDevice: null
    // });
    try {
      await printer.searchDevices();
      this.setData({
        isSearching: false,
      });
    } catch (err) {
      this.setData({
        isSearching: false,
      });
    }
  },
  // 3、连接设备
  async connectDevice() {
    if (this.data.isConnected) return;
    this.setData({
      isConnecting: true
    });
    try {
      await printer.connectDevice(this.data.currentDevice.deviceId);
    } catch (err) {
      this.setData({
        isConnecting: false
      });
    }
  },
  ReSearch() {
    this.setData({
      currentDevice: null,
      isSearching: true,
      isConnected: false,
      isConnecting: false
    });
    printer.reSearch().then(res => {
      this.setData({
        currentDevice: res
      });
      if (res) {
        this.setData({
          isSearching: false
        });
        this.connectDevice();
      }
    }).catch(() => {

    });
  },
  toPrint(e) {
    // this.setData({
    //   ShowPop: false,
    //   PrintPop: true,
    //   position: 'center',
    //   CustomStyle: 'width: 80%;height: 200px;margin-left:10%;margin-top:30vh;border-radius: 10px;'
    // });
    // return;
    wx.showLoading({
      title: '校验缴费中...',
      mask: true
    });
    const OrderNo = e.currentTarget.dataset.no;
    revenueApi.CheckQROrder(OrderNo).then(res => {
      wx.hideLoading();
      if (res.code === 200) {
        this.setData({
          ShowPop: false,
          PrintPop: true,
          position: 'center',
          CustomStyle: 'width: 80%;height: 200px;margin-left:10%;margin-top:30vh;border-radius: 10px;',
          OrderInfo: res.data
        });
      } else {
        wx.showToast({
          title: res.info,
          icon: 'none'
        });
      }
    })
  },
  Print() {
    if (!this.data.currentDevice) {
      wx.showToast({
        title: '已重新搜索蓝牙设备',
        icon: 'none'
      });
      this.ReSearch();
      return;
    }
    if (!this.data.isConnected) {
      wx.showToast({
        title: '启动连接中，请稍后打印',
        icon: 'none'
      });
      this.connectDevice();
      return;
    }
    wx.showLoading({
      title: '正在打印票据...',
      mask: true
    });
    // 初始化打印机 ESC @
    const initCmd = new Uint8Array([0x1B, 0x40]);
    // 设置居中 ESC a 1
    const alignCmd = new Uint8Array([0x1B, 0x61, 0x00]);
    const titleBytesGBK = iconv.encode("\t   采暖缴费单\n", 'gbk');
    const sep = this.getUint8Array("------------------------------------------------\n");
    const line = this.getUint8Array("\n\n");
    const CONS_NO = iconv.encode(`户    号: ${this.data.OrderInfo.ConsNo}\n`, 'gbk');
    const CONS_NAME = iconv.encode(`户    名: ${this.data.OrderInfo.ConsName}\n`, 'gbk');
    const Charge_Date = iconv.encode(`收款时间: ${this.data.OrderInfo.PayTime}\n`, 'gbk');
    const USER_NAME = iconv.encode(`收 费 员：${this.data.OrderInfo.OperatorName}\n`, 'gbk');
    const OrderNo = iconv.encode(`支付单号: ${this.data.OrderInfo.OrderNo}\n\n`, 'gbk');
    // const OrderNo = iconv.encode(`支付单号: 3GEA2025092510481701353\n\n`, 'gbk');
    const titleColumn = iconv.encode("年度\t单价\t供暖面积  应收金额\n", 'gbk');
    const details = [];
    for (let i = 0; i < this.data.OrderInfo.Detail.length; i++) {
      const item = this.data.OrderInfo.Detail[i];
      const itemValue = iconv.encode(`${item.HeatDuration}  ${item.Price}      ${item.HeatArea}      ${item.AccountMoney}\n`, 'gbk');
      details.push(...itemValue);
    }
    const OrderMoney = iconv.encode(`金额总计: ￥${this.data.OrderInfo.OrderMoney}\n`, 'gbk');
    const DiscountCost = iconv.encode(`优惠金额: ￥${this.data.OrderInfo.DiscountCost}\n`, 'gbk');
    const DelayCost = iconv.encode(`违 约 金: ￥${this.data.OrderInfo.DelayCost}\n`, 'gbk');
    const AccountMoney = iconv.encode(`实付金额: ￥${this.data.OrderInfo.AccountMoney}\n`, 'gbk');
    const payType = iconv.encode(`付    款: 线下扫码支付\n`, 'gbk');
    const company = iconv.encode(`${this.data.OrderInfo.CompanyName}\n`, 'gbk');
    const phone = iconv.encode(`客服热线：${this.data.OrderInfo.CompanyPhone}\n\n\nn\n`, 'gbk');

    // 合并所有指令和文本数据
    const fullBuffer = new Uint8Array([
      ...initCmd,
      ...alignCmd,
      ...line,
      ...titleBytesGBK,
      // 0x0D,
      ...sep,
      ...CONS_NO,
      ...CONS_NAME,
      ...Charge_Date,
      ...USER_NAME,
      ...OrderNo,
      ...sep,
      ...titleColumn,
      ...sep,
      ...details,
      ...sep,
      // ...line,
      ...OrderMoney,
      ...DiscountCost,
      ...DelayCost,
      ...AccountMoney,
      ...payType,
      ...sep,
      ...company,
      ...phone,
      0x1D, 0x56, 0x42, 0x00 // 全切纸指令（如果打印机支持）
    ]);
    this.DoPrint(fullBuffer.buffer);
  },
  async DoPrint(buffer) {
    try {
      await printer.print(buffer);
      wx.showToast({
        title: '打印成功'
      });
    } catch (err) {
      wx.showToast({
        title: '打印失败',
        icon: 'none'
      });
    }
  },
  DoPrintChunk(buffer) {
    const {
      deviceId,
      serviceId,
      characteristicId
    } = this.data;

    const MAX_PACKET_SIZE = 20; // 单次写入最大字节数，通常建议20字节[4](@ref)
    let offset = 0;
    const sendNext = () => {
      if (offset >= buffer.byteLength) {
        wx.hideLoading();
        return;
      };
      const packet = buffer.slice(offset, offset + MAX_PACKET_SIZE);
      offset += MAX_PACKET_SIZE;
      wx.writeBLECharacteristicValue({
        deviceId: deviceId,
        serviceId: serviceId,
        characteristicId: characteristicId,
        value: packet,
        success: (res) => {
          console.log('写入成功', res);
          sendNext();
        },
        fail: (err) => {
          wx.hideLoading();
          console.error('写入失败', err);
        }
      });
    }
    sendNext();
  },
  getUint8Array(str) {
    const buffer = new ArrayBuffer(str.length);
    const dataView = new Uint8Array(buffer);
    for (let i = 0; i < str.length; i++) {
      dataView[i] = str.charCodeAt(i);
    }
    return dataView;
  },
  /************ 蓝牙打印功能 ********************/
})